/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.app.service.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.yanlight.app.dal.dao.MenuDAO;
import com.yanlight.app.dal.entity.Menu;
import com.yanlight.app.model.MenuItem;
import com.yanlight.app.response.MenuListResponse;
import com.yanlight.app.service.MenuService;

/**
 * 
 *
 * @author haolw
 * @time 2017/08/18
 */
@Service
public class MenuServiceImpl implements MenuService {
	@Autowired
	private MenuDAO menuDAO;

	@Override
	public MenuListResponse findList(Collection<Integer> menuIds) {
		MenuListResponse response = null;
		if (!CollectionUtils.isEmpty(menuIds)) {
			response = new MenuListResponse();
			List<Menu> menuList = menuDAO.findAll(menuIds);
			if (!CollectionUtils.isEmpty(menuList)) {
				Map<Integer, MenuItem> menuMap = new HashMap<Integer, MenuItem>(8);
				MenuItem item;
				for (Menu menu : menuList) {
					item = new MenuItem();
					Integer parentId = menu.getParentId();
					Integer id = menu.getId();
					item.setId(menu.getId());
					item.setParentId(parentId);
					item.setName(menu.getName());
					item.setUrl(menu.getUrl());
					menuMap.put(id, item);
					if (parentId.equals(0)) {
						response.addMenu(item);
					}
				}
				for (Entry<Integer, MenuItem> entry : menuMap.entrySet()) {
					MenuItem menu = entry.getValue();
					Integer parentId = menu.getParentId();
					if (parentId > 0) {
						MenuItem parentMenu = menuMap.get(parentId);
						parentMenu.addSubMenu(menu);
					}
				}
			}
		}
		return response;
	}
}
